<template>
  <div class="playedu-tree">
    <a-tree
      draggable
      :blockNode="true"
      :selectable="false"
      :treeData="treeData"
      @dragenter="onDragEnter"
      @drop="onDrop"
    />
  </div>
</template>

<script setup lang="ts">
import { message, Tree, Tooltip } from "ant-design-vue";
import { ref, watch, h } from "vue";

interface Option {
  key: string | number;
  title: any;
}

interface Props {
  data: CourseHourModel[];
  onRemoveItem: (id: number) => void;
  onUpdate: (arr: any[]) => void;
}

const props = defineProps<Props>();

const treeData = ref<Option[]>([]);
const loading = ref<boolean>(true);

// 先定义函数，再使用它们
const removeItem = (id: number) => {
  if (id === 0) {
    return;
  }
  props.onRemoveItem(id);
};

const checkTree = (hours: CourseHourModel[]) => {
  const arr: Option[] = [];
  for (let i = 0; i < hours.length; i++) {
    arr.push({
      title: h('div', { class: 'd-flex' }, [
        h('div', { class: 'd-flex' }, [
          h('i', {
            class: 'iconfont icon-icon-video',
            style: {
              fontSize: '16px',
              color: 'rgba(0,0,0,0.3)',
            }
          }),
          h('div', { class: 'tree-video-title mr-24' }, hours[i].name)
        ]),
        h(Tooltip, { placement: 'top', title: '可拖拽排序' }, {
          default: () => h('i', {
            class: 'iconfont icon-icon-drag mr-16',
            style: { fontSize: '24px' }
          })
        }),
        h('i', {
          class: 'iconfont icon-icon-delete',
          style: { fontSize: '24px' },
          onClick: () => removeItem(hours[i].rid)
        })
      ]),
      key: hours[i].rid,
    });
  }
  treeData.value = arr;
};

const onDrop = (info: any) => {
  const dropKey = info.node.key;
  const dragKey = info.dragNode.key;
  const dropPos = info.node.pos.split("-");
  const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
  
  const loop = (
    data: any[],
    key: any,
    callback: (node: any, i: number, data: any[]) => void
  ) => {
    for (let i = 0; i < data.length; i++) {
      if (data[i].key === key) {
        return callback(data[i], i, data);
      }
      if (data[i].children) {
        loop(data[i].children, key, callback);
      }
    }
  };
  
  const data = [...treeData.value];
  let isTop = false;

  for (let i = 0; i < data.length; i++) {
    if (data[i].key === dragKey) {
      isTop = true;
    }
  }

  // Find dragObject
  let dragObj: any;
  let dragLength = info.dragNode.props.pos.split("-").length;
  let dropLength = info.node.props.pos.split("-").length;

  if (!info.dropToGap) {
    // Drop on the content
    if (
      (dropPosition == 0 && dropPos.length == 3) ||
      (dropPosition == 0 && dropPos.length == 2 && dragLength == 2)
    ) {
      // 不做任何操作
    } else {
      loop(data, dragKey, (item, index, arr) => {
        arr.splice(index, 1);
        dragObj = item;
      });
      loop(data, dropKey, (item) => {
        item.children = item.children || [];
        // where to insert 示例添加到头部，可以是随意位置
        item.children.unshift(dragObj);
      });
    }
  } else if (
    (info.node.props.children || []).length > 0 && // Has children
    info.node.props.expanded && // Is expanded
    dropPosition === 1 // On the bottom gap
  ) {
    loop(data, dragKey, (item, index, arr) => {
      arr.splice(index, 1);
      dragObj = item;
    });
    loop(data, dropKey, (item) => {
      item.children = item.children || [];
      // where to insert 示例添加到头部，可以是随意位置
      item.children.unshift(dragObj);
    });
  } else {
    if (
      (dragLength == 3 && dropLength == 2) ||
      (dragLength == 2 && dropLength == 3)
    ) {
      return;
    }
    loop(data, dragKey, (item, index, arr) => {
      arr.splice(index, 1);
      dragObj = item;
    });
    let ar: any[] = [];
    let i: number = 0;
    loop(data, dropKey, (_item, index, arr) => {
      ar = arr;
      i = index;
    });
    if (dropPosition === -1) {
      ar.splice(i, 0, dragObj);
    } else {
      ar.splice(i + 1, 0, dragObj);
    }
  }
  treeData.value = data;
  const keys = data.map((item: any) => item.key);
  props.onUpdate(keys);
};

const onDragEnter = (info: any) => {
  console.log(info);
};

// 最后设置 watch，确保所有函数都已定义
watch(
  () => props.data,
  (hours) => {
    if (hours && hours.length === 0) {
      return;
    }
    checkTree(hours || []);
  },
  { immediate: true, deep: true }
);
</script>

<style scoped>

</style>